package com.qyhl.webtv.module_microvideo.shortvideo.user;

import android.Manifest;
import android.os.Bundle;
import android.text.style.TextAppearanceSpan;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.ViewCompat;
import androidx.core.view.ViewPropertyAnimatorListener;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.flyco.tablayout.SlidingTabLayout;
import com.google.android.material.appbar.AppBarLayout;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.SpanUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.microvideo.ShortVideoUserBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.module_microvideo.R;
import com.qyhl.webtv.module_microvideo.R2;
import com.qyhl.webtv.module_microvideo.shortvideo.user.fragment.ShortVideoUserFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;

/**
 * 个人中心
 */
@Route(path = ARouterPathConstant.SHORT_VIDEO_USER)
public class ShortVideoUserActivity extends BaseActivity implements ShortVideoUserCenterContract.ShortVideoUserCenterView {
    @BindView(R2.id.head_icon)
    RoundedImageView headIcon;
    @BindView(R2.id.user_nickname)
    TextView userNickname;
    @BindView(R2.id.toolbar)
    Toolbar toolbar;
    @BindView(R2.id.appBar)
    AppBarLayout appBar;
    @BindView(R2.id.tabLayout)
    SlidingTabLayout tabLayout;
    @BindView(R2.id.view_pager)
    ViewPager viewPager;
    @BindView(R2.id.bottom_bar)
    RelativeLayout bottomBar;
    @BindView(R2.id.user_praise)
    TextView userPraise;
    @BindView(R2.id.title)
    TextView mTitle;
    @BindView(R2.id.tab_bg)
    RelativeLayout tabLayoutBg;

    private Adapter fragmentAdapter;

    private List<String> nameList = new ArrayList<>();

    private BottomBarStatus bottomBarStatus = BottomBarStatus.EXPAND;

    @Autowired(name = "userName")
    String userName;

    @Autowired(name = "id")
    String activityId;

    private ShortVideoUserCenterPresenter mPresenter;

    private boolean isRunning = false;

    private List<Fragment> fragmentList;

    private CollapsingToolbarLayoutState state = CollapsingToolbarLayoutState.EXPANDED;

    private ShortVideoUserBean mBean;

    private enum BottomBarStatus {
        EXPAND,
        COLLAPSED
    }

    private enum CollapsingToolbarLayoutState {
        EXPANDED,
        COLLAPSED,
        INTERNEDIATE
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setSupportActionBar(toolbar);

    }

    @Override
    protected int getContentView() {
        return R.layout.micro_activity_short_video_user;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.fullScreen(true).init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new ShortVideoUserCenterPresenter(this);
        initView();

    }

    @Override
    protected void setListener() {
        setListeners();
        mPresenter.getUserInfo(userName);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (android.R.id.home == item.getItemId()) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initView() {
        fragmentList = new ArrayList<>();
        fragmentList.add(ShortVideoUserFragment.newInstance(activityId, userName, 4));
        fragmentList.add(ShortVideoUserFragment.newInstance(activityId, userName, 5));
    }

    private void setListeners() {
        headIcon.setOnClickListener(v -> {
            showSimpleLoading();
            mPresenter.getUserInfo(userName);
        });

        appBar.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
            if (verticalOffset == 0) {
                if (state != CollapsingToolbarLayoutState.EXPANDED) {
                    state = CollapsingToolbarLayoutState.EXPANDED;//修改状态标记为展开
                    mTitle.setText("");
                    tabLayout.setIndicatorColor(getResources().getColor(R.color.micro_short_video_blue));
                    tabLayout.setUnderlineColor(getResources().getColor(R.color.micro_short_video_blue));
                    tabLayout.setTextSelectColor(getResources().getColor(R.color.micro_short_video_blue));
                    tabLayout.setTextUnselectColor(getResources().getColor(R.color.micro_short_video_unselect_color));
                    tabLayoutBg.setBackgroundResource(R.color.white);
                }
            } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                if (state != CollapsingToolbarLayoutState.COLLAPSED) {
                    state = CollapsingToolbarLayoutState.COLLAPSED;//修改状态标记为折叠
                    if (mBean != null) {
                        mTitle.setText(mBean.getNickName());
                    }
                    tabLayout.setIndicatorColor(getResources().getColor(R.color.white));
                    tabLayout.setUnderlineColor(getResources().getColor(R.color.white));
                    tabLayout.setTextSelectColor(getResources().getColor(R.color.white));
                    tabLayout.setTextUnselectColor(getResources().getColor(R.color.white));
                    tabLayoutBg.setBackgroundResource(R.color.micro_short_video_user_collapsed_bg);
                }
            } else {
                if (state != CollapsingToolbarLayoutState.INTERNEDIATE) {
                    mTitle.setText("");
                    state = CollapsingToolbarLayoutState.INTERNEDIATE;//修改状态标记为中间
                }
            }
        });
    }

    @Override
    public void setUserInfo(ShortVideoUserBean bean) {
        dismissLoading();
        mBean = bean;
        userNickname.setText(bean.getNickName());
        Glide.with(this)
                .load(bean.getLogo())
                .apply(new RequestOptions().error(R.drawable.comment_head_default).placeholder(R.drawable.comment_head_default))
                .into(headIcon);

        nameList.clear();
        nameList.add("作品" + bean.getWorksCount());
        nameList.add("榜单");
        viewPager.setAdapter(fragmentAdapter = new Adapter(getSupportFragmentManager(), fragmentList, nameList));
        tabLayout.setViewPager(viewPager);


        SpanUtils spanUtils = new SpanUtils(this);
        spanUtils.append(bean.getLikeCount() + "").setSpans(new TextAppearanceSpan(this, R.style.micro_short_video_praise_num))
                .append("次被赞\t\t\t").setSpans(new TextAppearanceSpan(this, R.style.micro_short_video_praise_txt))
                .append(bean.getwRankingCount() + "").setSpans(new TextAppearanceSpan(this, R.style.micro_short_video_praise_num))
                .append("次周榜\t\t\t").setSpans(new TextAppearanceSpan(this, R.style.micro_short_video_praise_txt))
                .append(bean.getmRankingCount() + "").setSpans(new TextAppearanceSpan(this, R.style.micro_short_video_praise_num))
                .append("次总榜").setSpans(new TextAppearanceSpan(this, R.style.micro_short_video_praise_txt));
        userPraise.setText(spanUtils.create());
    }

    @Override
    public void setUserError(String msg) {
        dismissLoading();
        showToast(msg, 4);
        Glide.with(this.getApplicationContext())
                .load(R.drawable.comment_head_default)
                .into(headIcon);
    }

    @OnClick(R2.id.shoot_btn)
    public void onViewClicked() {
        String activityStatus = CommonUtils.getInstance().getShortVideoState();
        switch (activityStatus) {
            case "BEGINNING":
                MPermissionUtils.requestPermissionsResult(ShortVideoUserActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO}, new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {

                        CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                            @Override
                            public void login(boolean isLogin) {
                                if (isLogin) {
                                    if (StringUtils.isMi8()) {
                                        Bundle bundle = new Bundle();
                                        bundle.putString("id", activityId);
                                        RouterManager.router(ARouterPathConstant.SHORT_VIDEO_SHOOT2,bundle);
                                    } else {

                                        Bundle bundle = new Bundle();
                                        bundle.putString("id", activityId);
                                        RouterManager.router(ARouterPathConstant.SHORT_VIDEO_SHOOT,bundle);
                                    }
                                } else {
                                    Toasty.normal(ShortVideoUserActivity.this, "尚未登录或登录已失效！").show();
                                    RouterManager.routerLogin(ShortVideoUserActivity.this, 0);
                                }
                            }

                            @Override
                            public void error(String s) {

                            }
                        });

                    }

                    @Override
                    public void onPermissionDenied() {
                        MPermissionUtils.showTipsDialog(ShortVideoUserActivity.this);
                    }
                });
                break;
            case "END":
                showToast("活动已结束！", 4);
                break;
            default:
                showToast("活动未开始！", 4);
                break;
        }

    }

    /**
     * 通过滑动距离判断上滑还是下滑来展开收起拍摄按钮
     *
     * @param dy 滑动
     */
    public void showHideBottombar(int dy) {
        if (!isRunning) {
            if (dy > 10) {  //上滑
                if (bottomBarStatus == BottomBarStatus.EXPAND) {
                    bottomBarStatus = BottomBarStatus.COLLAPSED;
                    //执行收起
                    ViewCompat.animate(bottomBar)
                            .translationYBy(StringUtils.dip2px(this, 70))
                            .setDuration(300)
                            .setListener(new ViewPropertyAnimatorListener() {
                                @Override
                                public void onAnimationStart(View view) {
                                    isRunning = true;
                                }

                                @Override
                                public void onAnimationEnd(View view) {
                                    isRunning = false;
                                }

                                @Override
                                public void onAnimationCancel(View view) {

                                }
                            });
                }
            } else if (dy < -10) { //下拉
                if (bottomBarStatus == BottomBarStatus.COLLAPSED) {
                    bottomBarStatus = BottomBarStatus.EXPAND;
                    //执行展开
                    ViewCompat.animate(bottomBar)
                            .translationYBy(StringUtils.dip2px(this, -70))
                            .setDuration(300)
                            .setListener(new ViewPropertyAnimatorListener() {
                                @Override
                                public void onAnimationStart(View view) {
                                    isRunning = true;
                                }

                                @Override
                                public void onAnimationEnd(View view) {
                                    isRunning = false;
                                }

                                @Override
                                public void onAnimationCancel(View view) {

                                }
                            });
                }
            }
        }
    }

    class Adapter extends FragmentPagerAdapter {
        private List<Fragment> fragmentList;
        private List<String> names;


        public Adapter(FragmentManager fm, List<Fragment> fragmentList, List<String> names) {
            super(fm);
            this.fragmentList = fragmentList;
            this.names = names;
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return names.get(position);
        }
    }
}
